<?php

namespace app\demo\service;

use app\demo\enum\Sex;
use app\demo\enum\Grade;
use app\demo\model\Example as Model;

class ImportDemo {

    private $model;

    private static $instance;

    private function __construct() {
        $this->model = new Model();
    }

    public static function instance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function cols($sheet) {
        $cols = [
            'name_cn' => [
                "title" => '中文名',
                "default" => "小王",
                "verify" => "require|chs",
                "desc" => "必填，只能输入汉字",
            ],
            'name_en' => [
                "title" => '英文名',
                "default" => "xiaowang",
                "verify" => "require|chsDash",
                "desc" => "必填，只能输入汉字、字母、数字和下划线_及破折号-",
            ],
            'sex' => [
                "title" => '性别',
                'default' => '男',
                'verify' => 'require|in:男,女',
                "desc" => "必填，男/女",
            ],
            'age' => [
                "title" => '年龄',
                'default' => '18',
                'verify' => 'require|positiveInteger',
                "desc" => "必填，正整数",
            ],
            'hobby' => [
                "title" => '爱好',
                'default' => '阅读',
                'verify' => 'require|in:写作,阅读',
                "desc" => "必填，写作/阅读",
            ],
            'intro' => [
                "title" => '简介',
                'default' => '个人简介',
                'verify' => 'require',
                "desc" => "必填，如：姓名、曾用名、出生日期、籍贯、出生地、民族、现有文化程度、家庭现住址、现在工作单位和担任的社会职务、有何专业技术职称等基本情况。",
            ],
        ];
        return $cols;
    }

    public function row($sheet, $row_data) {
        $data = [
                "grade" => Grade::code($sheet),
                "sex" => Sex::code($row_data["sex"]),
            ] + $row_data;
        $res = $this->model->addRow($data);
        return $res ? true : '导入失败';
    }

    public function rows($rows_data) {
        $datas = [];
        foreach ($rows_data as $id => $data) {
            $datas[] = [
                    "grade" => Grade::code($data["sheet"]),
                    "sex" => Sex::code($data["row"]["sex"]),
                ] + $data["row"];
        }
        $this->model->addRows($datas);
        return true;
    }

}